package com.woniu.service.impl;

import com.woniu.dao.UserDao;
import com.woniu.entity.Users;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

@Service
public class SecurityLoginService implements UserDetailsService {

    @Autowired(required = false)
    private PasswordEncoder passwordEncoder;
    @Autowired
    private UserDao userDao;
    /**
     * 根据传过来的account 查询数据库该账号信息，放入security框架中
     * @param account   页面的username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String account) throws UsernameNotFoundException {
        Users users = userDao.queryUserAuth(account);
        if(users==null){
            throw new UsernameNotFoundException("用户名和密码错误");
        }
        String auths = String.join(",", users.getAuths());
        return new User(users.getAccount(),passwordEncoder.encode(users.getPassword()),
                AuthorityUtils.commaSeparatedStringToAuthorityList(auths));
    }


}
